package com.kakame.netbook.common.interceptors;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.kakame.netbook.common.utils.LoggerUtil;

/**
 * <pre>
 * <b>desc:</b> 全局控制层拦截器
 * <b>auth:</b> 何家明
 * <b>date:</b> 2018年5月18日 下午11:39:55
 * </pre>
 */
public class GlobalActionInterceptor implements Interceptor {
	public void intercept(Invocation inv) {
		HttpServletRequest request = inv.getController().getRequest();
		String reqIp = getIpAddr(request);
		LoggerUtil.Logger.debug("用户IP：" + reqIp);
		String reqUserAgent = request.getHeader("user-agent");
		LoggerUtil.Logger.debug("用户代理：" + reqUserAgent);
		inv.invoke();
	}

	/**
	 * <pre>
	 * <b>desc:</b> 获取用户真实IP地址<br><br> 不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址<br> 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值<br>
	 * <b>auth:</b> 何家明
	 * <b>date:</b> 2018年5月25日 下午4:58:32
	 * </pre>
	 * 
	 * @param request
	 * @return
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");

		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknow".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();

			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡获取本机配置的IP地址
				InetAddress inetAddress = null;
				try {
					inetAddress = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inetAddress.getHostAddress();
			}
		}

		// 对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
		if (null != ipAddress && ipAddress.length() > 15) {
			// "***.***.***.***".length() = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}

		return ipAddress;
	}
}